package stud.mpgame.server.game;

import stud.mpgame.net.command.AddPlayerCommand;
import stud.mpgame.net.command.ArrowKeyCommand;
import stud.mpgame.net.command.ReadyToGameCommand;

import stud.mpgame.net.description.ArrowKeyCommandMessageDescription;
import stud.mpgame.net.description.ReadyToGameMessageDescription;

import stud.mpgame.network.IMessageReceivedListener;
import stud.mpgame.network.Message;
import stud.mpgame.network.MessageDescription;
import stud.mpgame.network.NetworkMonitor;

import stud.mpgame.network.util.MessageFilter;

import stud.mpgame.snapshot.SnapshotManager;

/**
 * @author f.pavel91@gmail.com
 * @version 1.0
 */
public class GameCommandDispatcher {

    private NetworkMonitor networkMonitor;
    private SnapshotManager snapshotManager;

    public GameCommandDispatcher(NetworkMonitor networkMonitor, SnapshotManager snapshotManager) {
        this.networkMonitor = networkMonitor;
        this.snapshotManager = snapshotManager;

        MessageDescription.registerDescription(ArrowKeyCommandMessageDescription.getInstance());

        addReadyToGameCommandListener();
        addArrowKeyCommandListener();

    }

    private void addReadyToGameCommandListener() {
        MessageFilter messageFilter = new MessageFilter(ReadyToGameMessageDescription.getInstance());

        networkMonitor.getMessageDispatcher().addMessageReceivedListener(messageFilter,
                new IMessageReceivedListener() {
                    public void messageReceived(Message message) {
                        ReadyToGameCommand readyToGameCommand = (ReadyToGameCommand) message.getUserObject(ReadyToGameCommand.class);
                        snapshotManager.addCommand(readyToGameCommand);
                        snapshotManager.addCommand(new AddPlayerCommand(readyToGameCommand.getTime(), message.getFirstSession(), readyToGameCommand.getUserID()));
                    }
                }
        );
    }

    private void addArrowKeyCommandListener() {
        MessageFilter messageFilter = new MessageFilter(ArrowKeyCommandMessageDescription.getInstance());

        networkMonitor.getMessageDispatcher().addMessageReceivedListener(messageFilter,
                new IMessageReceivedListener() {
                    public void messageReceived(Message message) {
                        ArrowKeyCommand arrowKeyCommand = (ArrowKeyCommand) message.getUserObject(ArrowKeyCommand.class);
                        snapshotManager.addCommand(arrowKeyCommand);
                    }
                }
        );
    }

}
